using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager_1 : MonoBehaviour
{
    public static GameManager_1 Instance;

    [Header("游戏配置")]
    public int startingScore = 501;     // 初始分数
    public int minDartsToBuy = 9;       // 最小购买飞镖数
    public float freePlayTime = 300f;   // 免费游戏时间（秒）

    [Header("UI引用")]
    public UIManager_1 uiManager;

    [Header("游戏状态")]
    public bool isInGameArea = false;   // 是否在游戏区域
    public bool isPlaying = false;      // 是否正在游戏
    public bool hasFreePlay = true;     // 是否有免费次数
    public int currentScore;            // 当前分数
    public int remainingDarts;          // 剩余飞镖数
    public float timeRemaining;         // 剩余时间
    public bool isTimeUp = false;       // 时间是否结束

    private void Awake()
    {
        if (Instance == null)
            Instance = this;
        else
            Destroy(gameObject);

        // 加载玩家数据
        LoadPlayerData();
    }

    void Start()
    {
        ResetGame();
    }

    void Update()
    {
        if (isPlaying && !isTimeUp)
        {
            timeRemaining -= Time.deltaTime;
            if (timeRemaining <= 0)
            {
                timeRemaining = 0;
                isTimeUp = true;
                CheckGameStatus();
            }

            // 更新UI
            uiManager.UpdateGameUI();
        }
    }

    // 初始化或重置游戏
    public void ResetGame()
    {
        isPlaying = false;
        currentScore = startingScore;
        remainingDarts = minDartsToBuy;
        timeRemaining = freePlayTime;
        isTimeUp = false;
        uiManager.UpdateGameUI();
    }

    // 开始游戏
    public void StartGame()
    {
        if (hasFreePlay)
        {
            // 使用免费次数
            hasFreePlay = false;
            SavePlayerData();
            StartGameSession();
        }
        else if (GetCoins() >= 1)
        {
            // 扣除时空币
            SpendCoins(1);
            StartGameSession();
        }
        else
        {
            // 显示充值面板
            uiManager.ShowRechargePanel();
        }
    }

    // 开始游戏会话
    private void StartGameSession()
    {
        isPlaying = true;
        isTimeUp = false;
        remainingDarts = minDartsToBuy;
        timeRemaining = freePlayTime;
        currentScore = startingScore;
        
        uiManager.HideGameAreaPanel();
        uiManager.ShowGameUI();
    }

    // 处理飞镖得分
    public void AddScore(int score)
    {
        currentScore -= score;
        remainingDarts--;
        uiManager.UpdateGameUI();
        CheckGameStatus();
    }

    // 检查游戏状态
    private void CheckGameStatus()
    {
        if (currentScore == 0)
        {
            // 游戏胜利
            isPlaying = false;
            uiManager.ShowResultPanel(true);
        }
        else if (currentScore < 0 || (remainingDarts <= 0 && currentScore > 0))
        {
            // 游戏失败（爆靶或飞镖用完但分数未归零）
            isPlaying = false;
            uiManager.ShowResultPanel(false);
        }
        else if (isTimeUp)
        {
            // 时间结束
            isPlaying = false;
            uiManager.ShowRechargePanel();
        }
    }

    // 充值方法
    public void Recharge()
    {
        // 实际项目中应跳转到充值页面
        AddCoins(5); // 模拟充值5个时空币
        uiManager.HideRechargePanel();
        uiManager.UpdateGameUI();
    }

    // 玩家数据管理
    public int GetCoins()
    {
        return PlayerPrefs.GetInt("Coins", 0);
    }

    public void AddCoins(int amount)
    {
        PlayerPrefs.SetInt("Coins", GetCoins() + amount);
        SavePlayerData();
    }

    public void SpendCoins(int amount)
    {
        int currentCoins = GetCoins();
        if (currentCoins >= amount)
        {
            PlayerPrefs.SetInt("Coins", currentCoins - amount);
            SavePlayerData();
        }
    }

    public void SavePlayerData()
    {
        PlayerPrefs.SetInt("HasFreePlay", hasFreePlay ? 1 : 0);
        PlayerPrefs.Save();
    }

    public void LoadPlayerData()
    {
        hasFreePlay = PlayerPrefs.GetInt("HasFreePlay", 1) == 1;
    }
}